package com.starnet.infocollecter;

import java.util.ArrayList;

import com.starnet.interfaces.ConnectNetInterface;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * 监听网络的状态变化
 * @author zmp
 *
 */
public class NetStateBroadcastReceiver extends BroadcastReceiver
{
	
	private ArrayList<ConnectNetInterface> connectNetInterfaces = new ArrayList<ConnectNetInterface>();
	
	public NetStateBroadcastReceiver()
	{
		
	}
	
	public void addConnectNetInterface(ConnectNetInterface connectNetInterface)
	{
		if(connectNetInterfaces == null)
		{
			connectNetInterfaces = new ArrayList<ConnectNetInterface>();
		}
		connectNetInterfaces.add(connectNetInterface);
	}
	
	

	@Override
	public void onReceive(Context arg0, Intent arg1) 
	{
		try 
		{
			ConnectivityManager connectMgr = (ConnectivityManager) arg0.getSystemService(Context.CONNECTIVITY_SERVICE); 
			NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
			NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
			if ((mobNetInfo!=null&&mobNetInfo.isConnected()) || (wifiNetInfo!=null&&wifiNetInfo.isConnected())) 
			{ 
				//连上网络了
				if(connectNetInterfaces != null)
				{
					int len = connectNetInterfaces.size();
					for (int i = 0; i < len; i++) 
					{
					     ConnectNetInterface connectNetInterface = connectNetInterfaces.get(i);
					     connectNetInterface.connectNet();
					}
					this.connectNetInterfaces.clear();
					this.connectNetInterfaces = null;
				}
				arg0.unregisterReceiver(this);
			} 
		} catch (Exception e)
		{
			 e.printStackTrace();
		}
		
	}

}
